//index.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";

//获取应用实例
// const app = getApp()


const app = getApp()
let isIphoneX = app.globalData.isIphoneX;

Page({
  data: {
    // uqid:'',
    // motto: 'Hello World',
    // isMaskAuth:false, //授权遮罩
    userInfo: {},
    isPhoneAuth: false, //手机号授权遮罩提示
    // hasUserInfo: false,
    // canIUse: wx.canIUse('button.open-type.getUserInfo'),
    serviceinfo: [], //服务列表
    clickcall: false,
    kftel: '',
    isIphoneX:isIphoneX,
    cantclick:true
  },

  //服务详情  
  // serviceIntro: function(e) {
  //   var goods_id = e.currentTarget.dataset.id;
  //   wx.navigateTo({
  //     url: '/pages/serviceintro/serviceintro?goods_id=' + goods_id,
  //   })

  // },


  // //判断是否已经测评过
  // isPatient: function (){
  //   ajax("/api/index/is_patient", {
  //     data: {
  //       uqid: this.data.uqid,
  //       goods_id: this.data.serviceinfo[0].id
  //     },
  //     header: {
  //       'Accept': 'application/json', // 默认值
  //     },
  //   }, res => {
  //     // console.log(res);
  //     if (res.error == 0) {//获取进展 pid
  //       if (res.data.status == 0) { //1-已有进展 0-没有
  //         wx.setStorageSync("pid", res.data.pid)
  //         wx.navigateTo({
  //           url: '/pages/functionalimpairment/functionalimpairment',
  //         })
  //       } else if (res.data.status == 1){

  //         wx.setStorageSync("pid", res.data.pid)
  //         wx.navigateTo({
  //           url: '/pages/functionalimpairment/functionalimpairment',
  //         })

  //       }
  //     }
  //   })
  // },


  //输入的手机号提交
  getPhoneAdd: function () {
    var that = this;
    console.log(this.data.uqid)
    console.log(this.data.phone)
    console.log(this.data.goods_id)

    ajax("/api/index/phone_add", {
      data: {
        uqid: this.data.uqid,
        phone: '',
        goods_id: this.data.serviceinfo[0].id
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method:'POST'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid
        wx.setStorageSync("pid", res.data.pid)

       

        wx.navigateTo({
          url: '/pages/functionalimpairment/functionalimpairment',
        })
      } else if (res.error == 1) { //已有进展
        wx.setStorageSync("pid", res.data.pid)

      
        wx.navigateTo({
          url: '/pages/functionalimpairment/functionalimpairment',
        })
      }
    })
  },
  
  // 获取进展
  getProgress: function() {
    ajax("/api/index/user_patient", {
      data: {
        uqid: this.data.uqid,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      // console.log(res);
      if (res.error == 0) {
        //康复进度(0 - 没有找到进展 1 - 智能评测 2 - 线上预约 3 - 线下评测 4 - 康复方案 5 - 病例)
        console.log(res.data)
        console.log("aaaaaaaaaaaaaaaaaaaaa")

        if (res.data.schedule != 1) {
          // wx.showToast({
          //   title: '请先去智能测评！',
          //   icon: 'none',
          //   duration: 1000
          // })
          this.getPhoneAdd()

        } else if (res.data.schedule == 1){
          wx.navigateTo({
            url: '/pages/reserveintro/reserveintro?goods_id=' + res.data.goods_id,
          })
        }
      }
    })
  },


  todetails: function(e) {
    var index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '/pages/details/details?index=' + index,
    })
  },
  callphone: function() {
    ajax("/api/index/contact_phone", {
      data: {},
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'get'
    }, res => {
      console.log(res)
      if (res.error == 0) {
        this.setData({
          kftel: res.data.contact_phone
        });
        this.setData({
          clickcall: true
        })
      }
    })

  },
  refusecall: function() {
    this.setData({
      clickcall: false
    })
  },
  cancall: function() {
    this.setData({
      clickcall: false
    })
    wx.makePhoneCall({
      phoneNumber: this.data.kftel //仅为示例，并非真实的电话号码
    })
  },

  //事件处理函数
  // bindViewTap: function() {
  //   wx.navigateTo({
  //     url: '../logs/logs'
  //   })
  // },
  //首页信息显示
  getIndexInfo() {
    ajax("/api/index/good_list", {
      data: {},
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'get'
    }, res => {
      console.log(res)
      if (res.error == 0) {
        this.setData({
          serviceinfo: res.data
        });
      }
    })
  },

  // 分销添加
  addyaoqing:function(){
    ajax("/api/index/distribution", {
      data: {
        uqid:wx.getStorageSync('uqid'),
        yq_uqid: wx.getStorageSync('yq_uqid')
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'post'
    }, res => {
      console.log(res)
      if (res.error == 0) {
        // wx.showToast({
        //   title: '分销成功',
        //   icon: 'none',
        //   duration: 2000
        // })
      }
    })
  },


  onLoad: function (options) {

    // options 中的scene需要使用decodeURIComponent才能获取到生成二维码时传入的scene


    var scene = decodeURIComponent(options.scene)//参数二维码传递过来的参数
    var yq_uqid = options.yq_uqid // 参数二维码传递过来的场景参数
    // if(){}

    console.log("11111111")

    console.log(scene)

    console.log(yq_uqid)
    console.log("11111111")

    if (yq_uqid){
      this.setData({
        yq_uqid:yq_uqid
      })
      wx.setStorageSync('yq_uqid', yq_uqid )
    } else if (scene){
      this.setData({
        yq_uqid: scene
      })
      wx.setStorageSync('yq_uqid', scene)
    }

    this.getIndexInfo();
  },
  onHide(){
    this.setData({
      showaddresstc: false,
    })
  },

  onShow() {
    this.setData({
      clickcall: false,
      cantclick:true
    })

    var uqid=wx.getStorageSync('uqid')
    this.setData({
      uqid:uqid
    })

    var that=this
   
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy

        wx.setStorageSync("latitude", latitude)
        wx.setStorageSync("longitude", longitude)

      },
      fail: (res) => {
        this.setData({
          showaddresstc: true
        })
      },
    })

  },

  onPullDownRefresh: function() {
    console.log("sssssssss")

    wx.stopPullDownRefresh();
  },


  // 首页登录


  bindGetUserInfo(e) {

    if(this.data.cantclick == false){
      console.log("cantclick")
      return
    }

    this.setData({
      cantclick:false
    })

    var that = this;
    
    console.log("--------------")
    console.log(e)

    var style=e.currentTarget.dataset.style
    this.setData({
      style:style
    })

    if(style==0){
      var id=e.currentTarget.dataset.style
      this.setData({
        goods_id:id
      })
    }
    

    if (this.data.islogin) {
      // this.getPhoneAdd()

      if(style=='0'){
        this.getPhoneAdd()
      }else if(style=='1'){
        this.getProgress()
      }


    } else {
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        var code = wx.getStorageSync("code");

        ajax('/api/index/login', {
          data: {
            js_code: code,
            nickname: e.detail.userInfo.nickName,
            avatar: e.detail.userInfo.avatarUrl
          },
          header: {
            'Accept': 'application/json', // 默认值
          },
        }, res => {

          if (res.error == 0) {
            wx.setStorageSync("uqid", res.data.uqid)

            that.setData({
              uqid: res.data.uqid,
              session_key: res.data.session_key,
              islogin:true
            });
            this.isPhone();

            if (wx.getStorageSync('yq_uqid')){
              if (wx.getStorageSync('yq_uqid') != this.data.uqid){
                this.addyaoqing()
              }else{
                console.log('是本人')
              }
            }

          } else if (res.error == 4003) { //重复授权
            this.isPhone();
            that.setData({
              islogin:true
            })

            if (wx.getStorageSync('yq_uqid')) {
              if (wx.getStorageSync('yq_uqid') != this.data.uqid) {
                this.addyaoqing()
              } else {
                console.log('是本人')
              }
            }

          }
        })
      } else {

        this.setData({
          cantclick:true
        })

        wx.showToast({
          title: '请先授权！',
          icon: 'none',
          duration: 2000
        })

      }
    }


  },


  //判断是否授权手机号
  isPhone: function() {
    var that = this;
    var tel = wx.getStorageSync("tel");
    console.log("------------------------" + tel)
    if (tel == undefined || tel == '') { //用户没有授权手机号
      that.setData({
        isPhoneAuth: true
      });
    } else { //用户已经授权手机号
      that.setData({
        isPhoneAuth: false
      });
      this.getTelAdd();
      if(this.data.style=='1'){
        this.getProgress();
      }else if(this.data.style=='0'){
        this.getPhoneAdd()
      }
      
    }
  },

  //授权手机号
  getPhoneNumber(e) {
    this.setData({
      isPhoneAuth: false
    })
    console.log(this.data.session_key);

    if (e.detail.encryptedData) {
      ajax("/api/index/phone_decrypt", {
        data: {
          session: this.data.session_key,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
        method: 'POST'
      }, res => {
        // console.log(res);
        if (res.error == 0) {
          var tel = res.data.phoneNumber;
          wx.setStorageSync("tel", tel)
          if(this.data.style=='1'){
            this.getProgress();
          }else if(this.data.style=='0'){
            this.getPhoneAdd()
          }
          this.getTelAdd();
        }
      })

    } 
  },
  //拒绝授权手机号
  refuseUserInfo: function() {
    this.setData({
      isPhoneAuth: false
    });

    if(this.data.style=='1'){
      this.getProgress();
    }else if(this.data.style=='0'){
      this.getPhoneAdd()
    }

  },

  // 授权手机号提交
  getTelAdd: function () {
    var tel = wx.getStorageSync("tel");
    ajax("/api/index/phone_wx_sq_add", {
      data: {
        uqid: this.data.uqid,
        phone: tel,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'POST'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid
        console.log(res)
      }
    })
  },


})